<?php


/**
 * Form Errors Helper
 * Manages form error strings
 */
class tx_zlib_viewhelper_formErrors extends tx_zlib_abstract_viewhelper {

	/**
	 * Contains error messages grouped by field

	 * Example:
	 *
	 * $formErrors = array(
	 * 		'email_address' => array(
	 *			[0] => 'This field is mandatory'
	 *		)
	 *
	 *
	*/
	private $formErrors = array();
	private $errorsViewName = 'formerrors';

	/**
	 *
	 * @param array $errors
	 * @return tx_zlib_viewhelper_formErrors
	 */
	public function formErrors(array $errors = array())
	{
		if(!empty($errors)) {
			$this->formErrors = $errors;
		}
		
		return $this;
	}


	/**
	 * Renders an error message for the given form $field.
	 * Errors are rendered in the 'errors.phtml' view.
	 *
	 * @param <string> $field Form field name
	 * @return <mixed>
	 * Returns array of error messages, null if no errors are present.
	 * Returns the whole errors array if no $field is specified.
	 */
	public function get($field = null, $errorsViewName = null) {
		if($errorsViewName === null) {
			$errorsViewName = $this->errorsViewName;
		}

		if(is_string($field)) {
			if(isset($this->formErrors[$field])) {
				$this->getView()->elementErrors	= $this->formErrors[$field];
				return $this->getView()->render($errorsViewName);
			}
			else {
				return null;
			}
		}
		else {
			return $this->formErrors;
		}
	}

	/**
	 * Binds an error $message to the given form $field
	 *
	 * @param <type> $field
	 * @param <type> $message
	 */
	public function add($field, $message) {
		$this->formErrors[$field][] = $message;
	}


	/**
	 * Returns true if no errors have been set
	 */
	public function noErrors() {
		if(empty($this->formErrors)) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Change the errors view
	 */
	public function setErrorsView($viewName) {
		$this->errorsViewName = (string)$viewName;
	}

}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/zlib/views/helpers/class.tx_zlib_viewhelper_formErrors.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/zlib/views/helpers/class.tx_zlib_viewhelper_formErrors.php']);
}
